package com.zbcz.crm.sp

import android.content.Context
import android.content.SharedPreferences
import android.text.TextUtils
import com.google.gson.Gson
import com.zbcz.crm.bean.UserInfo

object SharedPreferencesManager {
    private const val PREF_NAME = "userInfoPref"
    private const val KEY_USER_INFO = "userInfo"
    private const val TOKEN = "token"

    private fun getSharedPreferences(context: Context): SharedPreferences {
        return context.getSharedPreferences(PREF_NAME, Context.MODE_PRIVATE)
    }

    fun saveUserInfo(context: Context, userInfo: UserInfo) {
        val gson = Gson()
        val userInfoJson = gson.toJson(userInfo)

        val editor = getSharedPreferences(context).edit()
        editor.putString(KEY_USER_INFO, userInfoJson)
        editor.apply()
    }

    fun getUserInfo(context: Context): UserInfo? {
        val gson = Gson()
        val userInfoJson = getSharedPreferences(context).getString(KEY_USER_INFO, null)

        return if (userInfoJson != null) {
            gson.fromJson(userInfoJson, UserInfo::class.java)
        } else {
            null
        }
    }

    fun putToken(token: String?, context: Context) {
        if (!TextUtils.isEmpty(token)) {
            val editor = getSharedPreferences(context).edit()
            editor.putString(TOKEN, token)
            editor.apply()
        }
    }

    fun getToken(context: Context): String? {
        return getSharedPreferences(context).getString(TOKEN, "")
    }

}
